package com.uyong.study.maze.ui;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;

public class MazeFrame extends JFrame implements ActionListener {

	private static final long serialVersionUID = 1L;

	private MazePanel mazePanel;
	private JButton genMazeButton;
	private JButton showPathButton;
	private JLabel operateLabel;
	private JLabel showUseTimeLabel;

	/** 是否生成了迷宫 */
	private boolean isGenerated = false;

	public static void main(String[] args) {
		new MazeFrame();
	}

	public MazeFrame() {
		super("迷宫");
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {}

		mazePanel = new MazePanel(41);
		setSize(mazePanel.getRow() * MazePanel.SIZE + 15, mazePanel.getRow() * MazePanel.SIZE + 70);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setLayout(null);
		mazePanel.setLocation(5, 38);
		add(mazePanel);
		genMazeButton = new JButton("生成迷宫");
		genMazeButton.setBounds(6, 8, 100, 30);
		genMazeButton.setBorder(BorderFactory.createEtchedBorder(Color.BLUE, Color.GRAY));
		genMazeButton.addActionListener(this);
		add(genMazeButton);
		showPathButton = new JButton("自动寻找路径");
		showPathButton.setBounds(140, 8, 100, 30);
		showPathButton.setBorder(BorderFactory.createEtchedBorder(Color.BLUE, Color.GRAY));
		showPathButton.addActionListener(this);
		add(showPathButton);
		operateLabel = new JLabel();
		operateLabel.setText("   操作：上下左右控制方向");
		operateLabel.setBounds(280, 8, 162, 30);
		operateLabel.setBorder(BorderFactory.createEtchedBorder(Color.BLUE, Color.GRAY));
		add(operateLabel);
		showUseTimeLabel = new JLabel("   用时：");
		showUseTimeLabel.setBounds(470, 8, 150, 30);
		showUseTimeLabel.setBorder(BorderFactory.createEtchedBorder(Color.BLUE, Color.GRAY));
		add(showUseTimeLabel);

		setResizable(false);
		setVisible(true);
		showUseTime();
	}

	private void showUseTime() {
		while (true) {
			showUseTimeLabel.setText("   用时：" + mazePanel.getUsedTime() + " s");
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand() == "生成迷宫") {
			isGenerated = true;
			mazePanel.buildMaze();
			mazePanel.repaint();
			genMazeButton.setFocusable(false);
			mazePanel.requestFocus();
		}
		if (isGenerated && e.getActionCommand() == "自动寻找路径") {
			mazePanel.searchPath();
		}
	}
}
